package eu.connect.jmswrapper;

import javax.jms.*;

import org.apache.activemq.ActiveMQConnectionFactory;

public class ConnectJMSSender implements MessageListener {
	
	private ConnectJMSInvokeMessage invokeMsg;
	private TopicConnection tConnection;
	private TopicSession tSession;
	private Topic topic;
	private Object lock;
	private ConnectJMSReturnMessage returnMsg;
	
	
	public ConnectJMSSender(ConnectJMSInvokeMessage invokeMsg, String topicName) throws Exception {
		this.invokeMsg = invokeMsg;
		this.lock = new Object();
		this.returnMsg = null;
		ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://" + TargetHost.getHost() + ":61616");
		this.tConnection = connectionFactory.createTopicConnection();
		this.tSession = tConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
		this.topic = tSession.createTopic("connect."+topicName);
		this.tConnection.start();
	}
	
	public ConnectJMSReturnMessage invoke() throws JMSException {
		
		ObjectMessage objMsg = tSession.createObjectMessage();
		objMsg.setObject(this.invokeMsg);
		
		TopicPublisher publisher = tSession.createPublisher(this.topic);
		
		synchronized (this.lock) {
			tConnection.start();
			publisher.publish(objMsg);
			
			String filter = "JMSCorrelationID = '" + objMsg.getJMSMessageID() + "'";
			TopicSubscriber subscriber = tSession.createSubscriber(this.topic, filter, true);
			subscriber.setMessageListener(this);
			
			try {
				this.lock.wait();
			}
			catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			tConnection.close();
		}
		
		tConnection.close();
		return this.returnMsg;
	}

	@Override
	public void onMessage(Message message) {
		
		synchronized (this.lock) {
			ObjectMessage objMsg = (ObjectMessage) message;
			
			try {
				this.returnMsg = (ConnectJMSReturnMessage)objMsg.getObject();
			}
			catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			this.lock.notifyAll();
		}
	}

}
